// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

console.log(allValues.length);

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 109; // m=109  hk=119
// 预测结果统计变量
let predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

// ✅ 计算周期：找出号码出现位置间隔
const calculateCycle = (numbers, currentNumber) => {
  const positions = [];
  numbers.forEach((num, idx) => {
    if (num === currentNumber) {
      positions.push(idx);
    }
  });

  const cycles = [];
  for (let i = 1; i < positions.length; i++) {
    cycles.push(positions[i] - positions[i - 1]);
  }
  return cycles;
};

// ✅ 周期性分析策略：从所有号码中筛选周期短的
const cycleAnalysisStrategy = (temp) => {
  const previousNumbers = temp.map((v) => v.number);
  const cycleResults = [];

  const cycleThreshold = 5; // 可以调大一点如 5
  allNumbers.forEach((num) => {
    const cycle = calculateCycle(previousNumbers, num);
    if (cycle.length > 0 && cycle.length <= cycleThreshold) {
      cycleResults.push(num);
    }
  });

  return cycleResults;
};

// ✅ 选择32个不重复号码，如果不足则补充
const select32Numbers = (cycleResults) => {
  const unique = new Set();

  for (let num of cycleResults) {
    if (typeof num === "number") num = num.toString().padStart(2, "0");
    if (typeof num === "string") num = num.padStart(2, "0");
    if (/^\d{2}$/.test(num)) unique.add(num);
  }

  let result = Array.from(unique);

  // 🚫 如果超过 32 个，就裁剪
  if (result.length > 32) {
    result = result.slice(0, 32);
  }

  // 🚨 如果不足 32 个，就补充
  if (result.length < 32) {
    const already = new Set(result);
    const candidates = allNumbers.filter((n) => !already.has(n));
    for (let i = 0; i < candidates.length && result.length < 32; i++) {
      result.push(candidates[i]);
    }
  }

  // ✅ 最终校验
  if (result.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${result.length} 个）`);
  }

  return result;
};


// ✅ 主循环：遍历每一期数据
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(index - windowSize, index)
    : allValues.slice(0, index);

  if (temp.length === 0) return;

  const cycleAnalysisResult = cycleAnalysisStrategy(temp);
  // console.log(`周期性分析结果: ${cycleAnalysisResult.join(",")}`);

  const selectedNumbers = select32Numbers(cycleAnalysisResult);
  // console.log(`选出的32个号码: ${selectedNumbers.join(",")}`);

  if (selectedNumbers.length !== 32) {
    throw new Error("选出的32个号码数量不正确");
  }

  try {
    const isPredictionCorrect = checkAccuracy(selectedNumbers, item.number);
    if (isPredictionCorrect) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
    predictResults.push(selectedNumbers);
  } catch (error) {
    console.error(`Error in checkAccuracy at index ${index}: ${error.message}`);
  }
});

// ✅ 输出统计
const total = predictResults.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
